import { modalSlideUpAtomsFamily as atomsFamily } from "@/components/composite/ModalSlideUp/main"
import styled from "@emotion/styled"
import { useAtomValue, useSetAtom } from "jotai"
import { cloneElement, DependencyList, ReactElement, useCallback, useEffect, useRef } from "react"
export function useModalSlideUp(name: Components.WhereIsTheModalSlideUp = "root") {
    const atoms = useAtomValue(atomsFamily(name))
    const state = useAtomValue(atoms.stateAtom)
    const open = useSetAtom(atoms.openAtom)
    const close = useSetAtom(atoms.closeAtom)

    return {
        state,
        open,
        close,
    }
}

const ModalContent = styled.div`
    display: flex;
    flex-direction: column;
    border-radius: 10rem 10rem 0 0;
    position: relative;
    align-items: stretch;
    overflow: hidden;
`

export function useModal({
    el,
    effects = [],
    name = "root",
    onClose,
}: {
    el: ReactElement<{ onClose?: () => void }>
    name?: Components.WhereIsTheModalSlideUp
    effects?: DependencyList
    onClose?: () => void
}) {
    effects = effects || []
    const { open, close, state } = useModalSlideUp(name)
    useEffect(() => {
        if (!state.isOpen) {
            onClose?.()
        }
    }, [state.isOpen, onClose])

    const containerRef = useRef<HTMLDivElement>(null)

    return useCallback(() => {
        open(
            <ModalContent ref={containerRef}>
                {cloneElement(el, {
                    onClose: close,
                })}
            </ModalContent>,
            {
                closeOnClickMask: true,
                closeOnEscape: false,
            },
        )
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, close, el, ...effects])
}
